//引入http模块 搭建http服务器
const http = require('http')
const { client } = require('websocket')

const server = http.createServer()
server.listen(3000, () => {
  console.log('服务器搭建成功')
})

//引入websocket server模块
const webSocketServer = require('websocket').server

//存储所有终端的连接
const clients = []

//创建websocket服务对象
const wsServer = new webSocketServer({ httpServer: server })

//监听连接请求 建立连接
//webSocketRequest
wsServer.on('request', webSocketRequest => {
  //当前连接 会话
  const connection = webSocketRequest.accept(null, 'accepted-origin')

  //把连接添加到终端
  clients.push(connection)

  //定时向客户端发送
  // setInterval(() => {
  //   connection.sendUTF('hello world' + new Date())
  // }, 1000)

  //监听客服端发送信息
  connection.on('message', msg => {
    //当前传输的是utf8类型数据
    if (msg.type == 'utf8') {
      //发送数据
      clients.forEach(client => {
        client.sendUTF(msg.utf8Data)
      })
    }
  })

  //当前会话 连接断开时候 触发事件
  connection.on('close', (reasonCode, description) => {
    console.log('断开了一个连接')
    //获取当前索引
    const index = clients.indexOf(connection)
    //删除
    clients.splice(index, 1)
  })

})